<template>
  <div class="app-container">
    <Pagetitle
      :title="pageTitle.title"
      :name="pageTitle.name"
      :btnName="pageTitle.btnName"
      @btnFun="btnFun"
    ></Pagetitle>
    <div class="filter-container">
      <Row>
        <!-- <Col :md="4">
        <Select
          v-model="timeSelectValue"
          placeholder="选择类型"
          @on-change="changeDateType()"
        >
          <template v-for="time in timeSelect">
            <Option
              :key="time.value"
              :value="time.value"
            >{{time.label}}</Option>
          </template>
        </Select>
        </Col> -->
        <Col :md="4">
        <DatePicker
          v-model="taskHistoryDate"
          type="month"
          :clearable="false"
          format="yyyy-MM"
          placeholder="完成日期"
          @on-change="search"
        ></DatePicker>
        <!-- <DatePicker
          :open="open"
          :value="taskHistoryDate"
          confirm
          :type="dateType"
          @on-change="handleChange"
          @on-clear="handleClear"
          @on-ok="handleOk"
          class="date-picker"
        >
          <a
            href="javascript:void(0)"
            @click="handleClick"
          >
            <template v-if="taskHistoryDate === ''">选择日期</template>
            <template v-else>{{ showDate() }}</template>
          </a>
        </DatePicker> -->
        </Col>
        <Col
          :md="20"
          class="search-btn"
        >
        <Button
          type="primary"
          @click="showSearchModal()"
        >高级搜索</Button>
        <Button
          @click="clearSearch()"
          class="clear-search"
        >清除搜索</Button>
        </Col>
      </Row>
    </div>
    <div class="table-container">
      <div class="total-score">总分<span>{{totalScore}}</span>分</div>
      <Table
        stripe
        :loading="dataTable.loading"
        :border="dataTable.border"
        :columns="dataTable.columns"
        :data="dataTable.data"
      >
      </Table>

      <Row class="mtop20">
        <Col
          :md="4"
          class="flex-start-center height-30 page"
        >
        <div>
          共{{count}}条
          <Select
            v-model="limit"
            size="small"
            class="lz-select-width"
            @on-change="changePageSize(1)"
          >
            <Option
              v-for="item in pageSizeSeletc"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
        </div>
        </Col>
        <Col
          :md="12"
          class="flex-center-center height-30"
        >
        <Page
          v-if="pageshow"
          :total="count"
          :page-size="limit"
          @on-change="changePageSize"
          size="small"
          show-elevator
        />
        </Col>
        <Col :md="8">

        </Col>
      </Row>
    </div>

    <Modal
      v-model="urlsModal"
      :closable="false"
      :footer-hide="true"
    >
      <div class="modal-content">
        <div class="modal-header">
          <span>下载文档</span>
          <a @click="closeModal()">
            <svg-icon icon-class="close" />
          </a>
        </div>
        <div class="modal-body">
          <template v-for="(url, i) in urls">
            <a
              :key="i"
              class="url"
              :href="url.fileUrl"
              target="_blank"
            >
              {{url.fileName}}
            </a>
          </template>

        </div>
      </div>
    </Modal>

    <Modal
      v-model="searchModal"
      :closable="false"
      :footer-hide="true"
    >
      <div class="modal-content">
        <Form
          ref="searchForm"
          :model="searchForm"
          :rules="ruleValidate"
          :label-width="80"
        >
          <div class="modal-header">
            <span>高级搜索</span>
            <a @click="closeModal()">
              <svg-icon icon-class="close" />
            </a>
          </div>
          <div class="modal-body">
            <Row>
              <Col :span="12">
              <FormItem
                label="品牌"
                prop="departmentId"
              >
                <Select
                  v-model="searchForm.brandId"
                  placeholder="全部品牌"
                >
                  <Option value="">全部品牌</Option>
                  <Option
                    v-for="(brand) in brandListSelect"
                    :key="brand.brandId"
                    :value="brand.brandId"
                  >{{brand.brandName}}</Option>
                </Select>
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col :span="12">
              <FormItem label="成本中心">
                <Select
                  v-model="searchForm.costCenterId"
                  placeholder="全部成本中心"
                >
                  <Option value="">全部成本中心</Option>
                  <template
                    v-for="brand in brandListSelect"
                    v-if="brand.brandId === searchForm.brandId"
                  >
                    <Option
                      v-for="(cost) in brand.costCenterList"
                      :key="cost.id"
                      :value="cost.id"
                    >{{cost.costCenterName}}</Option>
                  </template>
                </Select>
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col :span="12">
              <FormItem label="选择物料">
                <Select
                  v-model="searchForm.firstMaterialName"
                  placeholder="全部一级物料"
                >
                  <Option value="">全部一级物料</Option>
                  <Option
                    v-for="(first,index) in materialListSelect"
                    :key="index"
                    :value="first.firstMaterial"
                  >{{first.firstMaterial}}</Option>
                </Select>
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem>
                <Select
                  v-model="searchForm.materialId"
                  placeholder="全部二级物料"
                >
                  <Option value="">全部二级物料</Option>
                  <template v-for="material in materialListSelect">
                    <template v-for="second in material.secondMaterialList">
                      <Option
                        :key="second.id"
                        :value="second.id"
                        v-if="searchForm.firstMaterialName === second.firstMaterial"
                      >{{second.secondMaterial}}</Option>
                    </template>
                  </template>
                </Select>
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col
                :span="24"
                v-if="rolesId !== 5"
              >
              <FormItem label="人员">
                <RadioGroup
                  v-model="formItem.radio"
                  @on-change="changeUserRadioGrioup()"
                >
                  <Radio label="">默认</Radio>
                  <Radio
                    label="1"
                    v-if="rolesId !== 4"
                  >按审核人</Radio>
                  <Radio label="2">按工号</Radio>
                  <Radio label="3">按姓名</Radio>
                </RadioGroup>
              </FormItem>
              </Col>
              <Col
                :span="24"
                v-if="rolesId !== 5&& rolesId !==4 && rolesId !==3&&formItem.radio !== '2'&&formItem.radio !== '3'"
              >
              <FormItem label="部门">
                <RadioGroup v-model="searchForm.departmentId">
                  <Radio label="">全部</Radio>
                  <Radio
                    :label="depart.id"
                    v-for="depart in departmentListSelect"
                    :key="depart.id"
                  >{{depart.departmentName}}</Radio>
                </RadioGroup>
              </FormItem>
              </Col>
            </Row>
            <Row v-if="formItem.radio === '1'">
              <Col :span="12">
              <FormItem label="审核人">
                <Select
                  v-model="searchForm.auditId"
                  placeholder="全部审核人"
                >
                  <Option value="">全部审核人</Option>
                  <template v-for="(audit) in auditListSelect">
                    <Option
                      :key="audit.index"
                      :value="audit.auditId"
                      v-if="searchForm.departmentId === audit.departmentId"
                    >{{audit.auditName}}</Option>

                    <Option
                      :key="audit.index"
                      :value="audit.auditId"
                      v-else-if="searchForm.departmentId === ''"
                    >{{audit.auditName}}</Option>

                  </template>
                </Select>
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col
                :span="12"
                v-if="formItem.radio === '2'"
              >
              <FormItem label="员工">
                <Input
                  v-model="searchForm.userId"
                  placeholder="输入工号"
                ></Input>
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col
                :span="12"
                v-if="formItem.radio === '3'"
              >
              <FormItem label="姓名">
                <Input
                  v-model="searchForm.userName"
                  placeholder="输入姓名"
                ></Input>
              </FormItem>
              </Col>
            </Row>
            <Row v-if="formItem.radio === ''&&rolesId !== 5">
              <Col :span="12">
              <FormItem label="组别">
                <Select
                  v-model="searchForm.categoryName"
                  placeholder="全部组别"
                >
                  <Option value="">全部组别</Option>
                  <Option
                    v-for="(category) in categoryListSelect"
                    :key="category.id"
                    :value="category.categoryName"
                  >{{category.categoryName}}</Option>
                </Select>
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem label="职业/级别">
                <Select
                  v-model="searchForm.levelName"
                  placeholder="全部职业/级别"
                >
                  <Option value="">全部职业/级别</Option>
                  <Option
                    v-for="(level) in levelListSelect"
                    :key="level.index"
                    :value="level.levelName"
                  >{{level.levelName}}</Option>
                </Select>
              </FormItem>
              </Col>

            </Row>
            <Row>

              <Col :span="12">
              <FormItem label="时间">
                <!-- <Select
                  v-model="timeSelectValue"
                  placeholder="选择类型"
                  @on-change="changeDateType()"
                >
                  <template v-for="time in timeSelect">
                    <Option
                      :key="time.value"
                      :value="time.value"
                    >{{time.label}}</Option>
                  </template>
                </Select> -->
                <DatePicker
                  v-model="taskHistoryDate"
                  type="month"
                  :clearable="false"
                  placeholder="完成日期"
                ></DatePicker>
              </FormItem>
              </Col>
              <!-- <Col :span="4">
              <DatePicker
                :open="open"
                :value="taskHistoryDate"
                confirm
                :type="dateType"
                @on-change="handleChange"
                @on-clear="handleClear"
                @on-ok="handleOk"
                class="date-picker"
              >
                <a
                  href="javascript:void(0)"
                  @click="handleClick"
                >
                  <template v-if="taskHistoryDate === ''">选择日期</template>
                  <template v-else>{{ showDate() }}</template>
                </a>
              </DatePicker>
              </Col> -->
              <Col :span="24">
              <FormItem label="排序">
                <RadioGroup v-model="searchForm.sortKey">
                  <Radio label="finishTime">按时间</Radio>
                  <Radio label="taskScore">按分值</Radio>
                </RadioGroup>
              </FormItem>
              </Col>
            </Row>

          </div>
          <div class="modal-footer">
            <Button @click="closeModal()">取消</Button>
            <Button
              type="primary"
              @click="search()"
            >确定</Button>
          </div>
        </Form>
      </div>
    </Modal>

  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { fetchTaskHistory, fetchTaskHistoryContent } from "@/api/table";
import { Pagetitle, Model } from "@/components";
import format from "date-format";
export default {
  data() {
    return {
      pageshow: true,
      //总页码
      count: 0,
      //页码
      currentPage: 1,
      //总条数
      limit: 10,
      pageSizeSeletc: [
        {
          value: 10,
          label: "10条/页"
        },
        {
          value: 20,
          label: "20条/页"
        }
      ],
      modal1: false,
      pageTitle: {
        title: "任务历史"
      },
      totalScore: 0,
      dataTable: {
        loading: false,
        border: false,
        columns: [
          {
            minWidth: 100,
            title: "部门",
            key: "departmentName"
          },
          {
            minWidth: 100,
            title: "姓名",
            key: "name"
          },
          {
            minWidth: 100,
            title: "组别",
            key: "categoryName"
          },
          {
            minWidth: 100,
            title: "品牌",
            key: "brandName"
          },
          {
            minWidth: 100,
            title: "成本中心",
            key: "costCenterName"
          },
          {
            minWidth: 100,
            title: "一级物料",
            key: "firstMaterialName"
          },
          {
            minWidth: 100,
            title: "二级物料",
            key: "secondMaterialName"
          },
          {
            minWidth: 100,
            title: "数量",
            key: "materialCount"
          },
          {
            minWidth: 120,
            title: "完成时间",
            key: "materialCount",
            render: (h, params) => {
              return h(
                "div",
                format("yyyy-MM-dd", new Date(params.row.finishTime))
              );
            }
          },
          {
            minWidth: 100,
            title: "分值",
            key: "taskScore"
          },
          {
            minWidth: 100,
            title: "操作",
            render: (h, params) => {
              if (params.row.fileList.length > 0) {
                return h(
                  "Button",
                  {
                    props: {
                      type: "text",
                      size: "small"
                    },
                    on: {
                      click: () => {
                        if (params.row.fileList.length === 1) {
                          const href = params.row.fileList[0].fileUrl;
                          window.open(href, "_blank");
                        } else {
                          this.urlsModal = true;
                        }
                        this.urls = params.row.fileList;
                      }
                    }
                  },
                  "查看"
                );
              } else {
                return h("Span", "空");
              }
            }
          }
        ],
        data: []
      },
      urlsModal: false,
      urls: [],
      timeSelectValue: "1",
      timeSelect: [
        {
          value: "1",
          label: "按月份"
        }
        // {
        //   value: "2",
        //   label: "按年份"
        // },
        // {
        //   value: "3",
        //   label: "自定义"
        // }
      ],
      open: false,
      taskHistoryDate: "",
      dateType: "month",
      searchForm: {
        sortKey: "finishTime",
        startTime: "",
        endTime: "",
        brandId: "",
        userId: "",
        departmentId: "",
        costCenterId: "",
        firstMaterialName: "", //一级物料
        materialId: "", //二级物料
        categoryName: "",
        levelName: "",
        auditId: "",
        userName: ''
      },
      formItem: {
        radio: ""
      },
      brandListSelect: [],
      categoryListSelect: [],
      levelListSelect: [],
      materialListSelect: [],
      departmentListSelect: [],
      auditListSelect: [],
      searchModal: false,
      ruleValidate: {}
    };
  },
  components: {
    Pagetitle,
    Model
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.taskHistoryDate = format("yyyy-MM-dd", new Date());
      this.getTaskHistory();
      this.getTaskHistoryContent();
    },
    //分页
    changePageSize(index) {
      this.currentPage = index;
      this.getTaskHistory();
    },
    //日历start
    // changeDateType() {
    //   if (this.timeSelectValue === "1") {
    //     this.dateType = "month";
    //     this.open = true;
    //   } else if (this.timeSelectValue === "2") {
    //     this.dateType = "year";
    //     this.open = true;
    //   } else if (this.timeSelectValue === "3") {
    //     this.dateType = "daterange";
    //     this.open = true;
    //   }
    // },
    // showDate() {
    //   let newDate = "";
    //   newDate = this.taskHistoryDate;
    //   if (this.timeSelectValue === "3") {
    //     newDate = newDate[0] + " - " + newDate[1];
    //   }
    //   return newDate;
    // },
    // handleClick() {
    //   this.open = !this.open;
    // },
    handleChange(date) {
      this.getTaskHistory();
      // this.taskHistoryDate = date;
    },
    // handleClear() {
    //   this.open = false;
    // },
    // handleOk() {
    //   this.open = false;
    // },
    //日历end
    async getTaskHistory() {
      let start;
      let end;
      if (this.taskHistoryDate !== "") {
        const nowHistoryDate = format(
          "yyyy-MM",
          new Date(this.taskHistoryDate)
        );
        if (this.timeSelectValue === "3") {
          start = nowHistoryDate[0];
          end = nowHistoryDate[1];
        } else if (this.timeSelectValue === "2") {
          start = nowHistoryDate + "-01-01";
          end = nowHistoryDate + "-12-31";
        } else if (this.timeSelectValue === "1") {
          const spData = nowHistoryDate.split("-");
          start = nowHistoryDate + "-01";
          end = nowHistoryDate + "-" + this.mGetDate(spData[0], spData[1]);
        }
      }

      this.dataTable.loading = true;
      const res = await fetchTaskHistory({
        pageNo: this.currentPage,
        pageSize: this.limit,
        sortKey: this.searchForm.sortKey,
        startTime: start,
        endTime: end,
        brandId: this.searchForm.brandId,
        userId: this.searchForm.userId,
        costCenterId: this.searchForm.costCenterId,
        firstMaterialName: this.searchForm.firstMaterialName,
        materialId: this.searchForm.materialId,
        categoryName: this.searchForm.categoryName,
        levelName: this.searchForm.levelName,
        departmentId: this.searchForm.departmentId,
        auditId: this.searchForm.auditId,
        userName: this.searchForm.userName
      });
      this.closeModal();
      this.totalScore = res.data.totalScore;
      this.dataTable.loading = false;
      this.count = res.data.total;
      this.dataTable.data = [];
      if (res.data.list.length > 0) {
        res.data.list.forEach(item => {
          const data = {};
          data.brandName = item.brandName;
          data.categoryName = item.categoryName;
          data.costCenterName = item.costCenterName;
          data.departmentName = item.departmentName;
          data.finishTime = item.finishTime;
          data.firstMaterialName = item.firstMaterialName;
          data.name = item.name;
          data.secondMaterialName = item.secondMaterialName;
          data.materialCount = item.materialCount;
          data.taskScore = item.taskScore;
          data.fileList = item.fileList;
          this.dataTable.data.push(data);
        });
      }
    },
    async getTaskHistoryContent() {
      const res = await fetchTaskHistoryContent({
        userId: this.userId
      });
      this.brandListSelect = [];
      this.departmentListSelect = [];
      this.materialListSelect = [];
      this.categoryListSelect = [];
      this.levelListSelect = [];
      this.auditListSelect = [];
      res.data.brandList.forEach(item => {
        const data = {};
        data.brandName = item.brandName;
        data.brandId = item.id;
        data.costCenterList = item.costCenterList;
        this.brandListSelect.push(data);
      });
      res.data.materialList.forEach(item => {
        const data = {};
        data.firstMaterial = item.firstMaterial;
        data.secondMaterialList = item.secondMaterialList;
        this.materialListSelect.push(data);
      });
      res.data.departmentList.forEach(item => {
        const data = {};
        data.id = item.id;
        data.departmentName = item.departmentName;
        this.departmentListSelect.push(data);
      });
      res.data.categoryList.forEach(item => {
        const data = {};
        data.id = item.id;
        data.categoryName = item.categoryName;
        this.categoryListSelect.push(data);
      });
      res.data.levelList.forEach(item => {
        const data = {};
        data.id = item.id;
        data.levelName = item.levelName;
        this.levelListSelect.push(data);
      });
      if (res.data.auditList) {
        res.data.auditList.forEach(item => {
          const data = {};
          data.auditId = item.auditId;
          data.auditName = item.auditName;
          data.departmentId = item.departmentId;
          this.auditListSelect.push(data);
        });
      }
    },
    btnFun() {},
    resetForm(name) {
      this.$refs[name].resetFields();
    },
    closeModal(name) {
      if (name) {
        this.resetForm(name);
      }
      this.searchModal = false;
      this.urlsModal = false;
    },
    search() {
      this.currentPage = 1;
      this.pageshow = false;
      this.getTaskHistory();
      this.$nextTick(() => {
        this.pageshow = true;
      });
    },
    showSearchModal() {
      this.searchModal = true;
    },
    clearSearch() {
      this.searchForm = {
        sortKey: "finishTime",
        startTime: "",
        endTime: "",
        brandId: "",
        userId: "",
        departmentId: "",
        costCenterId: "",
        firstMaterial: "", //一级物料
        materialId: "", //二级物料
        categoryName: "",
        levelName: "",
        auditId: "",
        userName: ''
      };
      this.getTaskHistory();
    },
    changeUserRadioGrioup() {
      if (this.formItem.radio === "2") {
        this.searchForm.auditId = "";
        this.searchForm.levelName = "";
        this.searchForm.categoryName = "";
      } else if (this.formItem.radio === "1") {
        this.searchForm.userId = "";
        this.searchForm.levelName = "";
        this.searchForm.categoryName = "";
      } else if (this.formItem.radio === "3") {
        this.searchForm.userName = "";
        this.searchForm.levelName = "";
        this.searchForm.categoryName = "";
      } else {
        this.searchForm.auditId = "";
        this.searchForm.userId = "";
        this.searchForm.userName = "";
      }
    },
    mGetDate(year, month) {
      var d = new Date(year, month, 0);
      return d.getDate();
    }
  },
  computed: {
    ...mapGetters(["userId", "rolesId"])
  }
};
</script>
<style lang="less" scoped>
@import "~@/styles/mixin";
.clear-search {
  margin-left: 10px;
}
.group-user {
  color: @default-color;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 500;
}
.warning {
  margin-left: 30px;
  color: @primary-color;
}
.total-score {
  font-size: 16px;
  color: @default-color;
  margin-bottom: 20px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  span {
    color: @primary-color;
  }
}
.filter-container {
  border-radius: 8px;
  margin-top: 15px;
  background-color: #fff;
  padding: 20px;
}
.date-picker {
  width: 208px;
  line-height: 30px;
  margin-left: 10px;
}
.search-btn {
  display: flex;
  justify-content: flex-end;
}
</style>